package org.naxx.security.function.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.naxx.security.common.Configurable;
import org.naxx.security.function.FunctionType;
import org.naxx.security.function.FunctionTypeDefinitionLoader;
import org.naxx.security.function.FunctionTypeResolver;

public class FunctionTypeResolverImpl implements FunctionTypeResolver, Configurable {
	
	private Map<String, FunctionType> functions;
	private FunctionTypeDefinitionLoader functiontypeDefinitionLoader;
	
	public void setFunctionTypeDefinitionLoader(
			FunctionTypeDefinitionLoader functiontypeDefinitionLoader) {
		this.functiontypeDefinitionLoader = functiontypeDefinitionLoader;
	}

	public void configure() {
		this.initFunctionRepository();
	}

	public FunctionType resolve(String functionUri) {
		FunctionType result = this.functions.get(functionUri);
		if(result == null) {
			throw new IllegalArgumentException("Unable to resolve function type from" +
					" function uri '" + functionUri + "'");
		}
		return result;
	}
	
	private void initFunctionRepository() {
		Set<FunctionType> functionTypes = this.functiontypeDefinitionLoader.loadFunctionDefinitions();
		this.functions = new HashMap<String, FunctionType>(functionTypes.size());
		for(FunctionType functionType : functionTypes) {
			this.functions.put(functionType.getUri(), functionType);
		}
	}
}
